package org.mspring.mlog.web.interceptor;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mspring.mlog.common.SpaceConst;
import org.mspring.mlog.core.ServiceFactory;
import org.mspring.mlog.entity.SpaceInfo;
import org.mspring.mlog.entity.security.User;
import org.mspring.mlog.service.SpaceInfoService;
import org.mspring.mlog.service.security.UserService;
import org.mspring.mlog.web.module.web.ucenter.UCenter_AbstractWidget;
import org.mspring.mlog.web.security.SecurityUtils;
import org.mspring.platform.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

/**
 * 处理访问用户中心请求
 * 
 * @author Gao Youbo
 * @since 2013年7月16日
 */
public class UCenterContextInterceptor extends HandlerInterceptorAdapter {
    @Autowired
    private UserService userService;
    @Autowired
    private SpaceInfoService spaceInfoService;

    @SuppressWarnings("unchecked")
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // TODO Auto-generated method stub
        Object handlerBean = ((HandlerMethod) handler).getBean();
        if (!(handlerBean instanceof UCenter_AbstractWidget)) {
            return true;
        }
        UCenter_AbstractWidget widget = (UCenter_AbstractWidget) handlerBean;

        Map<String, String> uriTemplateVars = (Map<String, String>) request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
        String username = (uriTemplateVars != null) ? uriTemplateVars.get(widget.getUserNamePathVariable()) : null;
        if (StringUtils.isBlank(username)) {
            response.sendError(404);
            return false;
        }

        User spaceUser = ServiceFactory.getUserService().getUserByName(username);
        if (spaceUser == null) {
            response.sendError(404);
            return false;
        }
        SpaceInfo spaceInfo = ServiceFactory.getBean(SpaceInfoService.class).getByUser(spaceUser.getId());

        User currentUser = SecurityUtils.getCurrentUser();
        boolean mine = false;
        if (currentUser != null && currentUser.getId().equals(spaceUser.getId())) {
            mine = true;
        }

        request.setAttribute(SpaceConst.SPACE_MINE, mine);
        request.setAttribute(SpaceConst.SPACE_USER, spaceUser);
        request.setAttribute(SpaceConst.SPACE_URL, request.getContextPath() + "/u/" + spaceUser.getName());
        request.setAttribute(SpaceConst.SPACE_INFO, spaceInfo);

        widget.setMine(mine);
        widget.setSpaceUser(spaceUser);
        widget.setSpaceInfo(spaceInfo);
        return true;
    }

}
